<?php

namespace App\Admin\Controllers\App;

use App\Admin\Actions\Batches\BatchDisable;
use App\Admin\Actions\Batches\BatchEnable;
use App\Models\Application;
use App\Models\Payment;
use App\Models\Wechat;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\Controllers\AdminController;

class WechatController extends AdminController
{
    protected string $title = '微信管理';

    public function grid(): Grid
    {
        $model = Wechat::ofAdmin()
            ->with(['payment'])
            ->withCount(['users']);

        return Grid::make($model, function (Grid $grid) {
            $grid->disableBatchDelete(false);
            $grid->batchActions([
                new BatchEnable(Wechat::class),
                new BatchDisable(Wechat::class),
            ]);

            if (Admin::user()->isAdministrator()) {
                $grid->column('application.name', '所属应用');
            }
            $grid->column('name', '公众号名称');
            $grid->column('appid', 'AppId');
            $grid->column('payment.name', '商户名称');
            $grid->column('payment.mch_id', '商户号');
            $grid->column('status', '状态')
                ->bool();
            $grid->column('users_count', '用户数量');
            $grid->column('remark', '备注信息')
                ->textarea();
            $grid->column('created_at');
        });
    }

    public function form(): Form
    {
        return Form::make(Wechat::ofAdmin(), function (Form $form) {
            if (Admin::user()->isAdministrator()) {
                $form->select('application_id', '所属应用')
                    ->required()
                    ->options(Application::ofEnabled()->pluck('name', 'id'));
            }
            $form->text('name', '公众号名称')
                ->required();
            $form->text('appid', 'AppId')
                ->required()
                ->rules('required|alpha_num|size:18')
                ->help('微信授权域名：'.config('app.url'));
            $form->text('secret', 'AppSecret')
                ->rules('required|alpha_num|size:32')
                ->required();
            $form->select('payment_id', '关联支付')
                ->options(Payment::ofAdmin()->ofEnabled()->pluck('name', 'id'));
            $form->switch('status', '状态')
                ->default(1);
            $form->textarea('remark', '备注信息');
        });
    }
}
